package com.security.event;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.sql.DataSource;

/**
 * 领域事件发布器
 * @author 大忽悠
 * @create 2022/12/22 12:05
 */
@Slf4j
public class DomainEventPublisher {
    protected JdbcTemplate jdbcTemplate;
    protected final ObjectMapper objectMapper=new ObjectMapper();

    public DomainEventPublisher(DataSourceProperties dataSourceProperties) {
        DataSource dataSource = DataSourceBuilder.create()
                .username(dataSourceProperties.getUsername()).password(dataSourceProperties.getPassword())
                .driverClassName(dataSourceProperties.getDriverClassName())
                .url("jdbc:mysql://8.134.144.48:3306/authCenter?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=Asia/Shanghai")
                .build();
        jdbcTemplate=new JdbcTemplate(dataSource);
    }

    /**
     * 在当前事务提交前发布事件;
     */
    public void publishEvent(DomainEvent domainEvent){
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
            @Override
            public void beforeCommit(boolean readOnly) {
                log.info("发布的领域事件为: {}",domainEvent);
                String sql = String.format("insert into domain_event(event_desc,event_content) values('%s','%s')", domainEvent.getEventDesc(), domainEvent.getEventContent());
                jdbcTemplate.execute(sql);
            }
        });
    }
}
